package com.imu.purse.modules.trade.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.imu.common.exception.RRException;
import com.imu.core.base.BaseService;
import com.imu.core.redis.annotation.RedisLock;
import com.imu.enums.OrderTypeStatus;
import com.imu.enums.PStatus;
import com.imu.enums.TradeType;
import com.imu.purse.modules.trade.dao.YmbWithdrawMapper;
import com.imu.purse.modules.trade.entity.FundEntity;
import com.imu.purse.modules.trade.entity.TradeInfoEntity;
import com.imu.purse.modules.trade.entity.YmbWithdrawEntity;
import com.imu.purse.modules.trade.service.FundService;
import com.imu.purse.modules.trade.service.TradeInfoService;
import com.imu.purse.modules.trade.service.YmbWithdrawService;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 易买宝充值详情表
 * @author sunhongwei
 * @email sunhongwei@jshijian.com
 * @date 2018-07-02 23:47:18
 * Copyright (c) 2017 武汉极时间科技有限公司 版权所有 
 * Jshijian aloha CO.,LTD. All Rights Reserved. 
 */
@Service
public class YmbWithdrawServiceImpl extends BaseService<YmbWithdrawEntity> implements YmbWithdrawService
{
	@Override
    @Transactional
    public int save(final YmbWithdrawEntity entity)
	{
		entity.setOrderState(PStatus.Create.getType());
		entity.setCreateTime(System.currentTimeMillis());
		entity.setUpdateTime(System.currentTimeMillis());
    	return super.insert(entity);
	}
	
	@Override
	@Transactional
    public int update(final YmbWithdrawEntity entity) 
    {
    	entity.setUpdateTime(System.currentTimeMillis());
    	return mapper.updateByPrimaryKeySelective(entity);
    }
    
    @Override
	@Transactional
    public int saveUpdate(final YmbWithdrawEntity entity)
    {
    	int len = 0;
    	
    	if(1 > (len = this.update(entity)))
    	{
        	len = this.insert(entity);
    	}
    	
    	return len;
    }
    
 	@Override
	@Transactional
    public boolean delete(final String ...ids)
    {
    	if(ArrayUtil.isEmpty(ids)) return false;
    	
    	for (String id : ids) 
    	{
    		if(StrUtil.isBlank(id)) continue;
    		
    		if(NumberUtil.isNumber(id))
    		{
        		mapper.deleteByPrimaryKey(Long.valueOf(id));
    		}
		}
    	
    	return true;
    }
 	

 	@Override
	@Transactional
	@RedisLock(keys = "#key", expire = 30000, tryTimeout = 1000)
 	public void withdraw(final String key, final YmbWithdrawEntity dto, final Long userId)
 	{
 		YmbWithdrawEntity entity = this.findById(dto.getId());
 		if(null == entity || null == entity.getOrderState() || PStatus.Create.getType() != entity.getOrderState().intValue()) //审核通过 增加金额写记录
		{
 			throw new RRException("该订单已处理，不能重复处理", 6001);
		}
 		if(2 == dto.getOrderState())
		{
 			this.wfait(entity, userId);
		}
 		this.update(dto);
 	}
 	
 	private void wfait(final YmbWithdrawEntity dto, final Long userId)
 	{
 		if(null == userId || 0 >= userId || null == dto || null == dto.getUserId()) return;
 		FundEntity funEntity = fundService.findByUserId(dto.getUserId());
 		if(null == funEntity || null == funEntity.getBj()) throw new RRException("收款账户不存在，请核实", 6001);
 		FundEntity useEntity = fundService.findByUserId(userId);
 		if(null == useEntity || null == useEntity.getBj()) throw new RRException("付款账户不存在，请联系管理员", 6002);
 		
        //扣减易买宝 保存流水记录
        TradeInfoEntity tradeEntity = new TradeInfoEntity();
        tradeEntity.setId(null);
        tradeEntity.setOrderNo(dto.getId().toString());
        tradeEntity.setPayUserId(dto.getUserId());
        tradeEntity.setRecUserId(userId);
        tradeEntity.setMoney(dto.getBjNum());
        tradeEntity.setSmoney(funEntity.getBj());
        tradeEntity.setEmoney(funEntity.getBj().add(dto.getBjNum()));
        tradeEntity.setOrderType(OrderTypeStatus.BACK.getType());
        tradeEntity.setOrderState(PStatus.Finished.getType());
        tradeEntity.setYtfType(TradeType.BJ.getType());
        tradeEntity.setOrderCreate(new Date());
        tradeInfoService.save(tradeEntity);
        //扣减易买宝
        FundEntity fund = new FundEntity();
		fund.setUserId(dto.getUserId());
		fund.setBj(dto.getBjNum());
		fundService.upBjMoney(fund);
        
        //信息归集
        tradeEntity.setId(null);
        tradeEntity.setOrderNo(dto.getId().toString());
        tradeEntity.setPayUserId(userId);
        tradeEntity.setRecUserId(dto.getUserId());
        tradeEntity.setMoney(dto.getBjNum());
        tradeEntity.setSmoney(useEntity.getBj());
        tradeEntity.setEmoney(useEntity.getBj().subtract(dto.getBjNum()));
        tradeEntity.setOrderType(OrderTypeStatus.OUT.getType());
        tradeEntity.setYtfType(TradeType.BJ.getType());
        tradeEntity.setOrderCreate(new Date());
        tradeInfoService.save(tradeEntity);
        
        fund.setUserId(userId.longValue());
        fund.setBj(dto.getBjNum().multiply(new BigDecimal(-1)));
		fundService.upBjMoney(fund);
 	}
 	
    @Override
    public YmbWithdrawEntity findById(final Long id)
    {
    	if(null == id) return null;
    	return mapper.selectByPrimaryKey(id);
    }
    
    @Override
    public List<YmbWithdrawEntity> queryList(final YmbWithdrawEntity entity)
    {
    	if (entity.getPage() != null && entity.getLimit() != null)
    	{
            PageHelper.startPage(entity.getPage(), entity.getLimit());
        }
    	
    	return mapper.findByPage(entity);
    }
    
	@Autowired
	private YmbWithdrawMapper mapper;
	
	@Autowired
	private FundService fundService;

	@Autowired
	private TradeInfoService tradeInfoService;
}
